<template>
	<view class="goods-like">
		<view v-if="dataList.length" class="goods-list goods-list-3 single-column">
			<view class="goods-like-title">
				<text>邻居都爱买</text>
				<view @click="$util.redirectTo('/pages/goods/list/list', {order: 'sale_num', sort: 'desc'})">
					<text>查看更多</text>
					<text class="iconfont iconright"></text>
				</view>
			</view>
			
			<scroll-view class="goods-like-scroll" :scroll-x="true" :show-scrollbar="false">
				<view class="goods-like-item" v-for="(item, index) in dataList" :key="index" @click="toDetail(item)">
					<view class="wrap">
						<view class="goods-img">
							<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"></image>
						</view>
						
						<view class="goods-name">{{ item.goods_name }}</view>
						
						<view class="goods-price">
							<view class="discount-price">
								<text class="unit font-size-tag">{{ $lang('common.currencySymbol') }}</text>
								<text class="price font-size-toolbar">{{ showPrice(item).split('.')[0] }}</text><text>.{{ showPrice(item).split('.')[1] }}</text>
							</view>
							
							<view class="delete-price color-tip">
								<text class="unit">{{ $lang('common.currencySymbol') }}</text>{{ item.market_price > 0 ? item.market_price : item.price }}
							</view>
						</view>
						
						<!-- <button v-if="item.num <= 0" class="info-btn color-base-bg" @click.stop="cartNumChange('add', item)">加入购物车</button>
						<view class="careBox" v-if="item.num > 0">
							<text class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
							<input :value="item.num" readonly disabled="disabled" unselectable="on" />
							<text class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
						</view> -->
						
						<view class="careBox" v-if="item.goods_spec_format || !token">
							<view class="careBox-con">
								<button class="info-btn color-base-bg" @click.stop="getGoodsSkuDetail(item.sku_id)">选规格</button>
								<view v-if="item.num" class="tag-num">{{item.num}}</view>
							</view>
						</view>
						
						<view class="careBox" v-if="!item.goods_spec_format">
							<button v-if="item.num <= 0" class="info-btn color-base-bg" @click.stop="cartNumChange('add', item)">加入购物车</button>
							<text v-if="item.num > 0" class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
							<input v-if="item.num > 0" :value="item.num" readonly disabled="disabled" unselectable="on" />
							<text v-if="item.num > 0" class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<ns-login ref="login"></ns-login>
		<ns-goods-sku-category ref="goodSkuNew" @refresh="refreshGoodsSkuDetail" @toGoTo="toGoTo" @getGoodsList="getGoodsList"></ns-goods-sku-category>
	</view>
</template>

<script>
	import globalConfig from '@/common/js/golbalConfig.js';
	import nsLoading from '@/components/ns-loading/ns-loading.vue';
	import nsGoodsSkuCategory from '@/components/ns-goods-sku/ns-goods-sku-category.vue';
	
	// 商品推荐
	export default {
		name: 'ns-goods-like',
		components: {
			nsLoading,
			nsGoodsSkuCategory
		},
		data() {
			return {
				dataList: [],
				showLoading: false,
				cartList: [],
				goodsSkuDetail: {},
				cartFlag: false,
				token: ''
			};
		},
		mixins: [globalConfig],
		props: {
			auto: {
				type: Boolean,
				default: true
			},
		},
		created() {
			this.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
		},
		mounted() {
			if (this.auto) {
				this.getGoodsList();
			}
		},
		methods: {
			getGoodsList() {
				this.$api.sendRequest({
					url: '/api/goodssku/page',
					data: {
						page: 1,
						page_size: 10
					},
					success: res => {
						if (res.code == 0 && res.data) {
							this.dataList = res.data.list;
							this.getCartData();
						}
					}
				})
			},
			getCartData() {
				if (!uni.getStorageSync('token')) {
					this.$emit('netFinish', true);
					return;
				}
			
				this.$api.sendRequest({
					url: '/api/cart/lists',
					success: res => {
						if (res.code >= 0) {
							this.cartList = res.data;
			
							for (let goods_index in this.dataList) {
								let goods_item = this.dataList[goods_index],
									sku_id = goods_item.sku_id,
									num = 0,
									cart_id = '';
			
								for (let cart_index in this.cartList) {
									let cart_item = this.cartList[cart_index];
									if (sku_id == cart_item.sku_id) {
										num += cart_item.num;
										cart_id = cart_item.cart_id;
									}
								}
								goods_item.num = num;
								goods_item.cart_id = cart_id;
			
								if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
									goods_item.num = 0;
								}
							}
							this.$forceUpdate();
						}
					}
				});
			},
			goodsImg(imgStr) {
				let imgs = imgStr.split(',');
				return imgs[0] ? this.$util.img(imgs[0], { size: 'mid' }) : this.$util.getDefaultImage().default_goods_img;
			},
			imgError(index) {
				this.list[index].goods_image = this.$util.getDefaultImage().default_goods_img;
			},
			showPrice(data) {
				let price = data.discount_price;
				if (data.member_price && parseFloat(data.member_price) < parseFloat(price)) price = data.member_price;
				return price;
			},
			goodsTag(data) {
				switch (data.recommend_way) {
					case 1:
						return '新品';
						break;
					case 2:
						return '精品';
						break;
					case 3:
						return '推荐';
						break;
					default:
						return '';
				}
			},
			
			
			//获取购物车数量
			getCartCount() {
				this.$store.dispatch('getCartNumber').then((e) => {
					this.cartCount = e;
				})
			},
			// 刷新商品sku详情数据
			refreshGoodsSkuDetail(goodsSkuDetail) {
				Object.assign(this.goodsSkuDetail, goodsSkuDetail);
			},
			async getGoodsSkuDetail(skuId) {
				if (!uni.getStorageSync('token')) {
					this.$refs.login.open(this.currentRoute);
					return;
				}
				
				let res = await this.$api.sendRequest({
					url: '/api/goodssku/getInfoForCategory',
					async: false,
					data: {
						sku_id: skuId,
					}
				});
				
				let data = res.data;
				if (data) {
					this.goodsSkuDetail = data;
				
					if (this.skuId == 0) this.skuId = this.goodsSkuDetail.sku_id;
				
					this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
				
					this.goodsSkuDetail.show_price = this.goodsSkuDetail.discount_price;
				
					// 当前商品SKU规格
					if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
				
					// 商品SKU格式
					if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
				
					this.$refs.goodSkuNew.show("join_cart", this.goodsSkuDetail, () => {
						this.getCartCount();
					});
				} else {
					this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
				}
			},
			
			// 变更购物车数量
			cartNumChange(type, goods) {
				if (!uni.getStorageSync('token')) {
					this.$refs.login.open('/pages/goods/category/category');
					return;
				}
			
				let cartData = {
						num: 1,
						cart_id: goods.cart_id,
						sku_id: goods.sku_id
					},
					cartUrl = "", //类型 add--新增商品  edit--修改商品数量  delete--删除商品
					actionType,
					maxBuy = goods.max_buy,
					stock = maxBuy > 0 ? (maxBuy - goods.purchased_num) : goods.stock;
			
				var minBuy = 1;
				if (goods.min_buy > 1) minBuy = goods.min_buy;
				cartData.num = minBuy; // 最少购买量
			
				goods.unit = goods.unit || "件";
			
				if (type == 'add') {
			
					// 检测是否第一次加入购物车
					if (goods.cart_id) {
						actionType = "edit";
						cartUrl = '/api/cart/edit';
					} else {
						actionType = "add";
						cartUrl = '/api/cart/add';
					}
					if (stock == 0) {
						this.$util.showToast({
							title: '库存不足'
						});
						return;
					} else if (goods.cart_id && goods.num < stock) {
						cartData.num = ++goods.num;
					} else {
						if (maxBuy > 0 && (goods.purchased_num + goods.num) >= maxBuy) {
							this.$util.showToast({
								title: '该商品每人限购' + maxBuy + goods.unit + '，您已购买了' + goods.purchased_num + goods.unit
							});
							return;
						}
			
						if (maxBuy > 0 && goods.num > 0 && goods.num + cartData.num > maxBuy) {
							var diff = maxBuy - goods.num;
							if (diff > 0) {
								this.$util.showToast({
									title: '该商品每人限购' +
										maxBuy +
										goods.unit +
										'，购物车已加入了' +
										goods.num +
										goods.unit +
										'，还能购买' +
										diff +
										goods.unit
								});
							} else {
								this.$util.showToast({
									title: '该商品每人限购' + maxBuy + goods.unit
								});
							}
							return;
						}
					}
			
				} else if (type == 'minus') {
					cartData.num = goods.num - 1 ? goods.num - 1 : 0;
					cartUrl = cartData.num > 0 ? '/api/cart/edit' : '/api/cart/delete';
					actionType = cartData.num > 0 ? 'edit' : 'delete';
				}
			
				if (this.cartFlag) return false;
				this.cartFlag = true;
			
				this.shopDataChange(cartData);
			
				this.$api.sendRequest({
					url: cartUrl,
					data: cartData,
					success: res => {
						if (res.code >= 0) {
							if (res.data > 0) {
								this.$emit('getCartCount', true);
								this.$store.dispatch('getCartNumber');
								this.$store.dispatch('getCartPrice');
								this.$store.dispatch('getCartIds');
								
								if (!goods.cart_id || (cartData.num <= 0 && type == 'minus')) this.getGoodsList();
								
								
								if (actionType == "edit") {
									this.cartFlag = false;
									return false;
								}
								cartData.cart_id = actionType == "add" ? res.data : '';
								if (actionType == 'add') {
									this.$util.showToast({
										title: '加入购物车成功'
									});
								}
							} else {
								cartData.num = goods.num;
								this.$util.showToast({
									title: res.message
								});
							}
						}
			
						this.cartFlag = false;
					}
				});
			},
			shopDataChange(data) {
				for (var i = 0; i < this.dataList.length; i++) {
					var item = this.dataList[i];
					if (data.sku_id == item.sku_id) {
						item.num = data.num;
						item.cart_id = data.cart_id;
					}
				}
				this.$forceUpdate();
			},
			//  孙子向爷爷穿透事件
			toGoTo(){
				// this.getGoodsList();
				this.$emit('getCartCount', true);
			}
		},
	};
</script>

<style lang="scss" scoped>
	.goods-like {
		width: 100%;
		background-color: #FFFFFF;
		padding: 40rpx 0;
	}
	
	.goods-like-title {
		padding: 0 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		>text {
			font-size: $font-size-toolbar;
			font-weight: 600;
		}
		
		>view {
			font-size: $font-size-tag;
			color: $color-tip;
			
			.iconfont {
				position: initial;
				font-size: $font-size-tag;
			}
		}
	}
	
	.goods-like-scroll {
		width: 100%;
		line-height: 1;
		white-space: nowrap;
		margin-top: 30rpx;
	}
	
	.goods-like-item {
		display: inline-block;
		width: 200rpx;
		margin-right: 30rpx;
		vertical-align: top;
		
		&:first-child {
			margin-left: 30rpx;
		}
		
		&:last-child {
			margin-right: 30rpx;
		}
		
		.wrap {
			width: 100%;
			
			.goods-img {
				width: 200rpx;
				height: 200rpx;
				
				image {
					width: 100%;
					height: 100%;
				}
			}
			
			.goods-name {
				font-weight: bold;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				margin-top: 10rpx;
			}
			
			.goods-price {
				.discount-price {
					line-height: 1;
					margin-top: 12rpx;
					color: #FF1919;
					font-weight: 600;
				}
				
				.delete-price {
					font-size: 20rpx;
					text-decoration: line-through;
					line-height: 1;
					margin-top: 10rpx;
				}
			}
			
			.info-btn {
				width: 182rpx;
				height: 70rpx;
				margin: 0;
				color: #FFFFFF;
				line-height: 70rpx;
				padding: 0;
				font-size: 26rpx;
			}
			
			.careBox {
				width: 182rpx;
				height: 70rpx;
				margin-top: 40rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				
				.careBox-con {
					width: 100%;
					height: 100%;
					position: relative;
				}
			}
			
			.careBox input {
				font-size: 36rpx;
				font-weight: bold;
				width: 60rpx;
				padding: 0 8rpx 4rpx 4rpx;
				box-sizing: border-box;
				text-align: center;
			}
			
			.careBox .iconfont {
				font-size: 60rpx;
			}
			
			.tag-num {
				display: block;
				width: 40rpx;
				height:40rpx;
				line-height: 40rpx;
				background: #FF1919;
				text-align: center;
				color: #fff;
				border-radius: 50%;
				position: absolute;
				top: -20rpx;
				right: 20rpx;
				font-size: 24rpx;
			}
		}
	}
</style>
